﻿using AuthorizationApiSample.Data.Entities;
using AuthorizationApiSample.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace AuthorizationApiSample.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AccountsController : ControllerBase
    {
        private readonly ILogger<AccountsController> _logger;

        public AccountsController(ILogger<AccountsController> logger)
        {
            this._logger = logger;
        }

        [Authorize]
        [HttpGet("test")]
        public string TestToken()
        {
            return "OK";
        }

        [HttpPost("token")]
        public async Task<string> GetToken(ReqLoginUser loginUser, [FromServices] UserManager<UserEntity> userManager, [FromServices] SignInManager<UserEntity> signInManager)
        {
            var user = await userManager.FindByEmailAsync(loginUser.Email);
            //await userManager.FindByNameAsync(loginUser.UserName);//用户名
            //await this._userManager.FindByLoginAsync("", "");//第三方，Google等
            //扩展其他方式：手机号等
            if (user == null)
            {
                return "The user don't exist";
            }
            var result = await signInManager.PasswordSignInAsync(user, loginUser.PassWord, loginUser.RememberMe, true);
            if (result.Succeeded)
            {
                //string token = await this.HttpContext.GetTokenAsync("Google");
                var claims = await userManager.GetClaimsAsync(user);
                return CreateToken(claims);
            }
            else if (result.IsLockedOut)
            {//此用户被锁定

            }
            else if (result.RequiresTwoFactor)
            {//需要二次验证

            }
            else if (result.IsNotAllowed)
            {//不允许

            }
            return "error";
        }

        private string CreateToken(IList<Claim> claims)
        {
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("123456789123456789"));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
               issuer: "http://localhost:5000",//颁发token的web应用程序
               claims: claims,
               expires: DateTime.Now.AddMinutes(1),
               signingCredentials: creds);
            return new JwtSecurityTokenHandler().WriteToken(token);
        }
    }
}
